const qiniu = require('qiniu');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');

// 七牛云配置
const qiniuConfig = {
  regionId: 'z0',
  oss: 'qiniuyun',
  bucket: '3d-app',
  domain: 'http://3d-app-qiniu.dlmu.cc',
  qiniuConfig: {
    accessKey: 'XY7NulclFTE8ff15ORUTq-zRFhrfnSOxwnrGF6e7',
    secretKey: '3Pqaeoh1JmmSdhfpONLE3LcH6HJsl3Y2vl8lT-0D',
  },
  catePathSplit: '/design/',
};

// 初始化七牛云
const mac = new qiniu.auth.digest.Mac(qiniuConfig.qiniuConfig.accessKey, qiniuConfig.qiniuConfig.secretKey);
const config = new qiniu.conf.Config();
const bucketManager = new qiniu.rs.BucketManager(mac, config);

// 上传文件到七牛云
async function uploadToQiniu(filePath, fileName) {
  try {
    // 读取文件
    const fileStream = fs.createReadStream(filePath);
    const fileBuffer = await new Promise((resolve, reject) => {
      const chunks = [];
      fileStream.on('data', chunk => chunks.push(chunk));
      fileStream.on('end', () => resolve(Buffer.concat(chunks)));
      fileStream.on('error', reject);
    });

    // 生成七牛云的文件名
    const ext = path.extname(fileName);
    const key = `${qiniuConfig.catePathSplit}${Date.now()}${ext}`;

    // 上传到七牛云
    return new Promise((resolve, reject) => {
      bucketManager.put(
        fileBuffer,
        key,
        qiniuConfig.qiniuConfig.accessKey,
        {
          mimeType: mime.lookup(fileName)
        },
        (err, respBody, respInfo) => {
          if (err) {
            reject(err);
          } else {
            resolve(`${qiniuConfig.domain}${key}`);
          }
        }
      );
    });
  } catch (error) {
    console.error('上传文件到七牛云失败:', error);
    throw error;
  }
}

module.exports = {
  uploadToQiniu
}; 